﻿using MediatR;
using T.Vehicleservice.Domain.Dtos;
using T.Vehicleservice.Domain.T.Vehicleservice.Model;
using T.Vehicleservice.Read.API.Application.Command.TireUsageRecordCommand;
using T.Vehicleservice.Repository.Interface;

namespace T.Vehicleservice.Read.API.Application.CommandHandlers.TireUsageRecordCommandHandler
{
    public class TireUsageRecordShowCommandHandler : IRequestHandler<TireUsageRecordShowCommand, PageDto<TireUsageRecord>>
    {
        private readonly ITireUsageRecordRepository _repository;
        public TireUsageRecordShowCommandHandler(ITireUsageRecordRepository repository)
        {
            _repository = repository;
        }

        public async Task<PageDto<TireUsageRecord>> Handle(TireUsageRecordShowCommand request, CancellationToken cancellationToken)
        {
            var list = (await _repository.GetAllAsync()).Where(x => !x.IsDeleted);
            if (!string.IsNullOrEmpty(request.LicensePlateNumber))
            {
                list = list.Where(x => x.LicensePlateNumber.Contains(request.LicensePlateNumber));
            }
            if (!string.IsNullOrEmpty(request.TireBrand))
            {
                list = list.Where(x => x.TireBrand.Contains(request.TireBrand));
            }
            if (!string.IsNullOrEmpty(request.Specifications))
            {
                list = list.Where(x => x.Specifications.Contains(request.Specifications));
            }
            if (!string.IsNullOrEmpty(request.User))
            {
                list = list.Where(x => x.User.Contains(request.User));
            }
            if (request.UsedDate != null)
            {
                list=list.Where(x=>x.UsedDate==Convert.ToDateTime(request.UsedDate).AddDays(1));
            }
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                list=list.Where(x=>x.CompanyID==request.CompanyID);
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = list.Count();
            }
            PageDto<TireUsageRecord> page= new PageDto<TireUsageRecord>();
            page.TotalCount = list.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / (int)request.PageSize);
            page.list = list.OrderByDescending(o => o.CreatedDate).Skip((int)(request.PageIndex - 1) * (int)request.PageSize).Take((int)request.PageSize).ToList();
            return page;
        }
    }
}
